<?php
include_once('Smarty.class.php');
$main_smarty = new Smarty;
include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'ts.php');
include(mnminclude.'link.php');
include(mnminclude.'tags.php');
include(mnminclude.'user.php');
include_once(mnminclude.'utils.php');
include(mnminclude.'smartyvariables.php');
include(mnminclude.'csrf.php');
include_once(mnminclude.'mailer.php');

// require user to log in
force_authentication();
// sidebar
$main_smarty = do_sidebar($main_smarty);
// sessions used to prevent CSRF
$CSRF = new csrf();
define('pagename', 'submit_user'); 
$main_smarty->assign('pagename', pagename);

//if the user recommend something and then reco the owner
if (isset($_REQUEST['lid'])) {
	$main_smarty->assign('lid',$_REQUEST['lid']);
}
else {
	$main_smarty->assign('lid',0);
}

if (isset($_REQUEST['group'])) {
	$main_smarty->assign('group',$_REQUEST['group']);
}
else {
	$main_smarty->assign('group',0);
}

if (!isset($_POST['usernames'])) {
	//first time load this page
	//get group
	getgroup();
	$main_smarty->assign('site', 'http://');
	$main_smarty->assign('tpl_center', $the_template . '/submit_user');
	$main_smarty->display($the_template . '/pligg.tpl');
}

if(isset($_POST['usernames'])){
	checkdata(); //if error get back and die
	if ($_POST['action'] == 'checkduplicate') {
		checkduplicate();
	}

	if ($_POST['action'] == 'alreadydigg') {
		dealalreadydigg();
	}

	if ($_POST['action'] == 'diggexistuser') {
		$todigguserid = $_POST['todigguserid'];
		diggexistuser($todigguserid);
	}
	
	if ($_POST['action'] == 'createanddigg') {
		createanddigg();
	}
}
	
function checkdata() {
	global $db, $dblang, $current_user, $main_smarty, $the_template;
		$should_return = false;
		$url_is_valid = false;
		if (($_POST['site'] == '') ||($_POST['site'] == 'http://')) {
			$url_is_valid = true;
		}
		else {
			$url_is_valid = check_url($_POST['site']);
		}
		if (!$url_is_valid) {
			$main_smarty->assign('sitecheck','请输入可访问的网址(以http://开头)或保留为http://不变');
			$should_return = true;
		}
		if ($_POST['usernames'] == '') {
			$main_smarty->assign('namescheck','请输入您推荐的人的名字');
			$should_return = true;
		}
		if ((trim($_POST['email']) != '') && (!check_email(trim($_POST['email']))))  {
			$main_smarty->assign('emailcheck','请输入正确的email或留空');
			$should_return = true;
		}
		if ($_POST['title'] == '') {
			$main_smarty->assign('titlecheck','请输入标题');
			$should_return = true;
		}
		if ($_POST['desc'] == '') {
			$main_smarty->assign('desccheck','&nbsp请输入评论');
			$should_return = true;
		}
		//if (($_POST['usernames'] == '')||($_POST['title'] == '') || ((($_POST['email'] != '') && (!check_email($_POST['email'])))) || ($_POST['desc'] == '') || !$url_is_valid) {				
		if ($should_return) {
			$main_smarty->assign('usernames',$_POST['usernames']);
			$main_smarty->assign('email',$_POST['email']);
			$main_smarty->assign('site',$_POST['site']);		
			$main_smarty->assign('tags',$_POST['tags']);
	 		$main_smarty->assign('title',$_POST['title']);
	 		$main_smarty->assign('comment',$_POST['desc']);
			$main_smarty->assign('tpl_center', $the_template . '/submit_user');
			$main_smarty->display($the_template . '/pligg.tpl');
			die();
		}
}

function add_user(){
	global $db,$current_user;

	$new_user_login = uniqid($current_user->user_id);

	//$saltedpass=generateHash($new_user_login);//should change this line to make a different pwd
	$new_user_pwd = uniqid($current_user->user_id);
	$saltedpass=generateHash($new_user_pwd);
	$new_user_names = $new_user_login;
	if ($_POST['usernames'] != '') {
		$new_user_names = $_POST['usernames'];
	}
	$new_user_email = 'blank@blank.com';

	if (isset($_POST['email']) && $_POST['email']!= '') {	
		//if ((check_email(trim($_POST['email'])))) {
		if ((check_email_address(trim($_POST['email'])))) {

			if (!user_exists(trim($_POST['email']))) {

				$new_user_email = $_POST['email'];
				adduser_sendemail($new_user_email,$new_user_names,$new_user_login,$new_user_pwd);
				
			}


		}


	}

	$db->query("INSERT INTO " . table_users . " (user_login, user_names, user_level, user_email, user_pass, user_date, user_first_time) VALUES ('$new_user_login', '$new_user_names', 'normal', '$new_user_email', '$saltedpass', now(), 'true')");


	$sql = "SELECT user_id FROM " . table_users . " WHERE user_login = '".$new_user_login."';";


	$new_user_id = $db->get_var($sql);


	return $new_user_id;


}

function adduser_sendemail($new_user_email,$new_user_names,$new_user_name,$new_user_pwd) {
	global $current_user;
	$to       = $new_user_email; 
	$subject  = "=?UTF-8?B?".base64_encode($current_user->user_names .'在人物系统中向大家推荐了您')."?="; 
	$headers  = 'MIME-Version: 1.0' . "\r\n"; 
	$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n"; 
	$headers .= 'To: =?UTF-8?B?' .$new_user_names. '?= <' . $new_user_email .'>' . "\r\n"; 
	$headers .= 'From: =?UTF-8?B?' . base64_encode('青铜') . '?=' . ' <forestyaser@163.com>' . "\r\n"; 
	$headers .= 'Reply-To: Admin <forestyaser@163.com>' . "\r\n"; 
	$message .= $new_user_names . ': ' . "\r\n" . "\r\n";
	$message .= '  '. $current_user->user_names . '在人物系统中向大家推荐了您' . "\r\n\r\n" ;
	$message .= '  您可查看此推荐 ' . my_base_url . my_pligg_base . '/user.php?login=' . $new_user_name . '&view=recoby' . "\r\n\r\n";
	$message .= '  补充您的档案，并修改系统为您预设的用户名和密码 ' . my_base_url . my_pligg_base . '/profile.php ' . "\r\n\r\n";
	$message .= '  预设的用户名为:  '. $new_user_name . '  密码为： ' .$new_user_pwd . '  ' . "\r\n\r\n" ;
	$message .= '  您也可查看' . $current_user->user_names . '的档案 ' . my_base_url . my_pligg_base . '/user.php?login=' . $current_user->user_login . '&view=profile' . "\r\n\r\n";
	$message .= "\r\n\r\n" . '  人物系统致力于推荐有价值的人和物，欢迎您使用' . "\r\n\r\n";
	$message .= '  有任何疑问请咨询站务 青铜 forestyaser@163.com  谢谢！';
	return mail($to, $subject, $message, $headers);
	//if (mail($to, $subject, $message, $headers)) {echo 'ok';} else {echo 'bad';}
}

function add_site($site_url,$site_ownerid,$site_title) {
	global $db;
	if (($site_ownerid > 0) && ($site_url != "http://") && ($site_url != "")) {
		$sql = "INSERT INTO " . table_site . " (site_owner, site_url, site_title) VALUES ($site_ownerid, '$site_url', '$site_title')";
		$db->query($sql);
	}
}

function checkduplicate() {
	global $db, $dblang, $current_user, $offset, $page_size, $top_users_size,$main_smarty, $the_template;
	getduplicateusers(); //if there is duplicate user, load another tpl and die
	//if no user seems like the user he want to recommend, so create a new one directly
	createanddigg();
}

function getduplicateusers() {
	global $db, $dblang, $current_user, $offset, $page_size, $top_users_size,$main_smarty, $the_template;
	$main_smarty->assign('usernames',$_POST['usernames']);
	$main_smarty->assign('email',$_POST['email']);
	$main_smarty->assign('site',$_POST['site']);
	$main_smarty->assign('tags',$_POST['tags']);
	$main_smarty->assign('title',$_POST['title']);
	$main_smarty->assign('comment',$_POST['desc']);
	$main_smarty->assign('cur_page',get_current_page());
	$offset=(get_current_page()-1)*$top_users_size;
	$sqlquery = "SELECT count(*) FROM " . table_users . " where user_login LIKE '%".$_POST["usernames"]."%' OR user_names LIKE '%".$_POST["usernames"]."%'";
	if ($_POST['email'] != '') {
		$sqlquery = $sqlquery . " OR user_email = '".$_POST["email"]."'";
	}
	$rows = $db->get_var($sqlquery);
	if ($rows>0) {							
		$sqlquery = "SELECT * FROM " . table_users . " where user_login LIKE '%".$_POST["usernames"]."%' OR user_names LIKE '%".$_POST["usernames"]."%'";
		if ($_POST['email'] != '') {
			$sqlquery = $sqlquery . " OR user_email = '".$_POST["email"]."'";
		}
		$sqlquery = $sqlquery . " LIMIT $offset,$top_users_size";
		$searchsql = mysql_query($sqlquery);
		$userlist = array();
		$digger = array();
		while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($userlist, $row);
		foreach($userlist as $key => $val){
			$userlist[$key]['Avatar'] = get_avatar('large', "", $val['user_login'], $val['user_email']);
			$digger = user_digged($val['user_login'],$val['user_id']);
			$userlist[$key]['digged'] = $digger['digged'];
			$userlist[$key]['digger_id'] = $digger['digger_id'];
			$userlist[$key]['digger_digglinkid'] = $digger['digger_digglinkid'];
			$userlist[$key]['digger_digglinkvotes'] = $digger['digger_digglinkvotes'];
			$userlist[$key]['digger_digglinkcomments'] = $digger['digger_digglinkcomments'];
			$userlist[$key]['digger_login'] = $digger['digger_login'];
			$userlist[$key]['digger_names'] = $digger['digger_names'];
			$userlist[$key]['digger_Avartar'] = '';
			if ($digger['digger_id'] > 0) {
				$userlist[$key]['digger_Avatar'] = get_avatar('large',"",$digger['digger_login']);
			}
		}					
		$main_smarty->assign('userlist', $userlist);
		// show the template
		$main_smarty->assign('tpl_center', $the_template . '/submit_user_list');
		$main_smarty->display($the_template . '/pligg.tpl');		
		die();
	}
}

function dealalreadydigg() {
	global $db, $dblang, $current_user, $main_smarty, $the_template;
	require_once(mnminclude.'link.php');
	$todigglink = new Link();
	$todigglink->id = $_POST['digglinkid'];
	$todigglink->read();			
	//add vote
	if($todigglink->votes($current_user->user_id) == 0) {
		$group = $_REQUEST['group'];
		//$todigglink->insert_vote($current_user->user_id, '10');
		$todigglink->insert_vote($current_user->user_id, '10',$group);
		$todigglink->store();
		$todigglink->read(FALSE); 
	}//should add hint here that the user has already digged this person
	//add  comment
	$randkey = rand(1000000,100000000);
	if (strlen($_POST['desc']) > 0) {	
		$comment_desc = $_POST['usernames'] . "\r\n" . $_POST['title'];
		if (strlen(trim($_POST['tags'])) > 0) {
			$tags2desc = '标签：' . $_POST['tags'];
			$comment_desc = $comment_desc . "\r\n" . $tags2desc;
		}
		if ((strlen(trim($_POST['site'])) > 0) && (trim($_POST['site']) != 'http://')){
			$site2desc = '网址：' . $_POST['site'];
			$comment_desc = $comment_desc . "\r\n" . $site2desc;
		}
		$comment_desc = $comment_desc . "\r\n" . $_POST['desc'];
		$cid = add_comment($todigglink->id,$randkey,$current_user->user_id,$comment_desc);
		$todigglink->adjust_comment(1);
		$todigglink->store();
		$todigglink->read(FALSE);
	}
	if ($_POST['lid'] > 0) {
		$todigguserid = $db->get_var("SELECT owner_id FROM " . table_link_owner . " WHERE link_id=" . $todigglink->id);
		add_linkowner($_POST['lid'], $todigguserid);
	}
	header('location: ' . my_base_url . my_pligg_base . '/story.php?title=' . $todigglink->title_url . '#c' . $cid);
}

function diggexistuser($todigguserid) {
	global $db, $dblang, $current_user, $main_smarty, $the_template;
	if (!($todigguserid > 0)) {
		die('用户ID出错，请与站务青铜联系');
	}
	if ($todigguserid > 0) {
		require_once(mnminclude.'link.php');
		$todigglink = new Link();
		$todiggurl = my_base_url . my_pligg_base ."/user.php?uid=" . $todigguserid;
		$todigglink->url = $todiggurl;
		$todigglink->randkey = rand(10000,10000000);
		$todigglink->get($todiggurl);
		$todigglink->valid = true;
		$todigglink->category = get_category_id("人");
		$todigglink->status='published';
		$todigglink->published_date = time();
		$todigglink->author=$current_user->user_id;
		$todigglink->title = strip_tags(trim($_POST['title']));
		$todigglink->title_url = makeUrlFriendly($todigglink->title);
		$todigglink->tags = tags_normalize_string(strip_tags(str_replace('，',',',trim($_POST['tags']))));
		$todigglink->content = strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow);
		$todigglink->content = str_replace("\n", "<br />", $todigglink->content);
		$todigglink->link_summary = utf8_substr(strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow), 0, StorySummary_ContentTruncate - 1);
		$todigglink->link_summary = str_replace("\n", "<br />", $todigglink->link_summary);		
		$todigglink->store();
		totals_adjust_count('published', 1);
		$todigglink->read(FALSE);
		tags_insert_string($todigglink->id, $dblang, $todigglink->tags);
		//die('todigglink->id: ' . $todigglink->id . ' todigguserid: ' .$todigguserid);
		add_linkowner($todigglink->id, $todigguserid);
		if ($_POST['lid'] > 0) {
			add_linkowner($_POST['lid'], $todigguserid);
		}
		$todigglink->read(FALSE);
		if($todigglink->votes($current_user->user_id) == 0 && auto_vote == true) {
			$group = $_REQUEST['group'];
			//$todigglink->insert_vote($current_user->user_id, '10');
			$todigglink->insert_vote($current_user->user_id, '10', $group);
			$todigglink->store_basic();
			$todigglink->read(FALSE); 
		}
		if (strlen($_POST['desc']) > 0) {	
			add_comment($todigglink->id,rand(10000,10000000),$current_user->user_id,$_POST['desc']);
			$todigglink->adjust_comment(1);
			$todigglink->store();
			$todigglink->read(FALSE);
		}
		$todigglink->date = time();
		$todigglink->published_date = time();
		$todigglink->store();
		header('location: ' . my_base_url . my_pligg_base . '/story.php?id=' . $todigglink->id);
	}
}

function createanddigg() {
	global $db, $dblang, $current_user, $main_smarty, $the_template;
	$new_user_id = add_user();
	$todigguserid = $new_user_id;
	if (($_POST['site'] != '') && ($_POST['site'] != 'http://')) {
		add_site($_POST['site'],$new_user_id,$_POST['usernames'] . '的网址');
	}
	diggexistuser($todigguserid);
}


?>